//
//  EWUserInfoSettingViewController.m
//  haveSomethingToEat
//
//  Created by 陈 宁权 on 17/4/10.
//  Copyright © 2017年 陈 宁权. All rights reserved.
//

#import "EWUserInfoSettingViewController.h"
#import "EWTitleCommonCell.h"
#import "EWTitleCommonModel.h"
#import "EWImageCommonCell.h"
#import "EWChangePhoneNumberVC.h"
#import "EWLoginViewController.h"
#import "RCDChangePasswordViewController.h"
#import "RCDEditUserNameViewController.h"

@interface EWUserInfoSettingViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIButton *exitBtn;
@end

@implementation EWUserInfoSettingViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //增加观察者
    [self configNotification];
    //配置导航栏
    [self configNav];
    //配置tableview
    [self configTableView];
    //增加退出按钮
    [self configExitBtn];
}

- (void)configNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userNameChanged) name:NSNOTIFICATION_USERNAME_CHANGED object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(phoneNumberChanged) name:NSNOTIFICATION_PHONENUMBER_CHANGED object:nil];

}

- (void)userNameChanged
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:1 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)phoneNumberChanged
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:3 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)configNav
{
    [self.navigationItem setTitle:@"账户信息"];
}

- (void)configTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.view addSubview:self.tableView];
}

- (void)configExitBtn
{
    _exitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_exitBtn setTitle:@"退出当前账号" forState:UIControlStateNormal];
    [_exitBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_exitBtn setBackgroundColor:[UIColor whiteColor]];
    _exitBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_exitBtn addTarget:self action:@selector(exitSystem) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_exitBtn];
    
    [_exitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.offset(44);
    }];
}

- (void)exitSystem
{
    [[RCIMClient sharedRCIMClient] disconnect];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"loginToken"];
    
    EWLoginViewController *loginVC = [[EWLoginViewController alloc] init];
    [self presentViewController:loginVC animated:YES completion:nil];
}

#pragma mark UITableViewDataSource 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.item == 0) {
            EWImageCommonCell *cell = [EWImageCommonCell cellWithTableView:tableView];
            cell.backgroundColor = [UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
            cell.headingsText = @"头像";
            cell.subHeadingsImageUri = [RCIM sharedRCIM].currentUserInfo.portraitUri;
            return cell;
        }
        else{
            EWTitleCommonCell *cell = [EWTitleCommonCell cellWithTableView:tableView];
            
            cell.backgroundColor = [UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            if (indexPath.item == 1) {
                cell.headingText = @"用户名";
                cell.subheadingText = [RCIM sharedRCIM].currentUserInfo.name;
            }
            else if (indexPath.item == 2){
                cell.headingText = @"账号密码";
                cell.subheadingText = @"修改";
            }
            else{
                cell.headingText = @"手机号";
                cell.subheadingText = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userMobile"] stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
            }
            return cell;
        }
    }
    return nil;
}


#pragma mark UITableViewDelegate 代理方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //修改用户头像
    if (indexPath.item == 0) {
        UIAlertController *alertController=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *actionCamera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *pickerCamera = [[UIImagePickerController alloc] init];//初始化
            pickerCamera.sourceType=UIImagePickerControllerSourceTypeCamera;
            pickerCamera.allowsEditing = YES;//设置可编辑
            pickerCamera.showsCameraControls = YES;
            pickerCamera.cameraViewTransform = CGAffineTransformMakeScale(1.5, 1.5);
            pickerCamera.delegate = self;
            [self presentViewController:pickerCamera animated:YES completion:nil];
            
        }];
        
        UIAlertAction *actionPhotoLIbrary = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *pickerLibrary = [[UIImagePickerController alloc] init];
            pickerLibrary.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            pickerLibrary.allowsEditing = YES;//设置可编辑
            pickerLibrary.delegate = self;
            [self presentViewController:pickerLibrary animated:YES completion:nil];
            
            
        }];
        
        UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alertController addAction:actionCamera];
        
        [alertController addAction:actionPhotoLIbrary];
        
        [alertController addAction:cancelAction];
        
        UIPopoverPresentationController *popover = alertController.popoverPresentationController;
        
        if (popover) {
            UIImageView *imageView = [[UIImageView alloc] init];
            popover.sourceView = imageView;
            popover.sourceRect = imageView.bounds;
            popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
        }
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
    else if (indexPath.item == 1)//修改用户名
    {
        RCDEditUserNameViewController *changeUserNameVC = [[RCDEditUserNameViewController alloc] init];
        [self.navigationController pushViewController:changeUserNameVC animated:YES];
    }
    else if (indexPath.item == 2)//修改密码
    {
        RCDChangePasswordViewController *changePasswordVC = [[RCDChangePasswordViewController alloc] init];
        [self.navigationController pushViewController:changePasswordVC animated:YES];
    }
    else if (indexPath.item == 3){//修改手机号
        EWChangePhoneNumberVC *changePhoneNumberVC = [[EWChangePhoneNumberVC alloc] init];
        [self.navigationController pushViewController:changePhoneNumberVC animated:YES];
    }
        
}

#pragma mark UIImagePickerControllerDelegate 代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *timestamp = [NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]];
    //图片上传到云服务器
    NSString *key = [NSString stringWithFormat:@"%@_userIcon_%@.png",[RCIM sharedRCIM].currentUserInfo.userId,timestamp];
    UIImage *userImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    //设置图片圆角
    userImage = [userImage circleImage];
    //将用户头像保存到沙盒
    NSData *imageData = UIImageJPEGRepresentation(userImage, 0.5);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:key];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
    
    NSString *delkey = [[[RCIM sharedRCIM].currentUserInfo.portraitUri componentsSeparatedByString:@"/"] lastObject];
    NSLog(@"deleteKey=%@",delkey);
    //删除原来的图片
    [[BQUserDao shareObject] deleteImageWithKey:delkey andServiceReceiveResponseSuccess:^(id response) {
        [[SDImageCache sharedImageCache] removeImageForKey:[RCIM sharedRCIM].currentUserInfo.portraitUri withCompletion:^{
            
        }];
    }];
    
    //上传图片到腾讯云
    [SVProgressHUD showWithStatus:@"正在上传图片中..."];
    [[BQUserDao shareObject] uploadImageToTenCentWithImageData:imageData andKey:key andServiceReceiveResponseSuccess:^(id response) {
        
        NSString *portraitUri = [@"http://eatwhat-1253652883.cosgz.myqcloud.com/" stringByAppendingString:key];
        
        RCUserInfo *userInfo = [[RCDataBaseManager shareInstance] getUserByUserId:[RCIM sharedRCIM].currentUserInfo.userId];
        
        [SVProgressHUD showWithStatus:@"正在更新用户信息中..."];
        [[BQUserDao shareObject] updateUserInfoWithUserId:userInfo.userId andUserName:userInfo.name andUserMobile:[[NSUserDefaults standardUserDefaults] objectForKey:@"userMobile"] andPortraitUri:portraitUri andServiceReceiveResponseSuccess:^(id response) {
            
            [SVProgressHUD showSuccessWithStatus:@"更新用户图片成功"];
            [RCIM sharedRCIM].currentUserInfo.portraitUri = portraitUri;
            RCUserInfo *userInfo = [RCIM sharedRCIM].currentUserInfo;
            userInfo.portraitUri = portraitUri;
            [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:[RCIM sharedRCIM].currentUserInfo.userId];
            
            [RCDDataSource syncUserInfoWithUserId:userInfo.userId complete:^(BOOL result) {
                
            }];
            
            [[SDImageCache sharedImageCache] removeImageForKey:portraitUri withCompletion:^{
                //发送通知刷新用户头像cell
                [[NSNotificationCenter defaultCenter] postNotificationName:NSNOTIFICATION_USERICON_CHANGED object:nil];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
                    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                });
            }];
            
        } ServiceReceiveResponseFailed:^(id response) {
            [SVProgressHUD showErrorWithStatus:@"更新用户信息失败"];
        }];
        
        
    } ServiceReceiveResponseFailed:^(id response) {
        [SVProgressHUD showErrorWithStatus:@"上传用户头像失败，请稍后重试!"];
    }];
    
    
    
    //退出编辑图片页面
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
